package com.subframe7536.sa.security.filter;

import com.subframe7536.sa.entity.MyUserdetailEntity;
import com.subframe7536.sa.utils.JwtUtil;
import com.subframe7536.sa.utils.RedisCacheUtil;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author subframe7536
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisCacheUtil redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws IOException, ServletException, RuntimeException {
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String phone;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            phone = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("无效token");
        }
        //从redis中获取用户信息
        String redisKey = "login" + phone;
        MyUserdetailEntity loginUser = (MyUserdetailEntity) redisCache.get(redisKey);
        if (Objects.isNull(loginUser)) {
            //TODO logger
            throw new RuntimeException("用户未登录");
        }
        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
            new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }

}
